package sisicotren.ui.simulator;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.Observable;

import sisicotren.model.simulator.QueueNotification;
import sisicotren.ui.simulator.Queue;
import sisicotren.util.Log;

public class QueueBasicImpl extends Observable implements Queue {

	@Override
	public void update(Observable o, Object arg) {
		QueueNotification qn = (QueueNotification)arg;
		Log.print("QueueBasicImpl, update, novedad = [" + qn.getOp() + "]");
		this.size = qn.getSize();
		Log.print("QueueBasicImpl, update, size = [" + this.size + "]");
		this.action = qn.getOp();
		this.setChanged();
		this.notifyObservers();
	}

	@Override
	public void draw(Graphics g) {
		if(this.img == null)
			loadImage();
		
		Log.print("QueueBasicImpl, draw, size ["+ this.size + "]");
		
		if(this.action == "pool") {
			Color old = g.getColor();
			// TODO : desharcodear.
			g.setColor(Color.ORANGE);
			
			for(int i=this.size + 10; i >= 0; i--)
				g.fillRect(
					(int)(position.getX() + (i * 5)),
					(int)(position.getY() - (i * 20)), 
					this.getWidth(), 
					this.getHeight());
			
			g.setColor(old);
			
			if(this.size > 0)
				for(int i=this.size; i >= 0; i--) {
					boolean res = g.drawImage(img, 
							(int)(position.getX() + (i * 5)), 
							(int)(position.getY() - (i * 20)), 
							this.getWidth(), 
							this.getHeight(),
							Color.ORANGE,
							null);
					if(!res) {
						Log.print("QueueBasicImpl, draw, Pool (" + ((int)position.getX() + (i * 5)) + ", " +((int)position.getY() - (i * 20)) + ")");
					}
				}
		}
			
		if(this.action == "add")
			for(int i=this.size; i >= 0; i--) {
				boolean res = g.drawImage(img, 
					(int)(position.getX() + (i * 5)), 
					(int)(position.getY() - (i * 20)), 
					this.getWidth(), 
					this.getHeight(), 
					Color.ORANGE,
					null);
				if(!res) {
					Log.print("QueueBasicImpl, draw, Add (" + ((int)position.getX() + (i * 5)) + ", " +((int)position.getY() - (i * 20)) + ")");
				}
			}
		this.action = "";
	}

	private void loadImage() {
		img = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/img/silueta_small.png"));
	}
	
	@Override
	public Point getPosition() {
		return this.position;
	}

	@Override
	public void setPosition(Point p) {
		this.position = p;		
	}

	@Override
	public int getWidth() {
		return img == null ? 0 : img.getWidth(null) == -1 ? 40 : img.getWidth(null);
	}

	@Override
	public int getHeight() {
		return img == null ? 0 : img.getHeight(null) == -1 ? 40 : img.getHeight(null);
	}
	
	public ScreenElement copy(){ 
		QueueBasicImpl queueCpy = new QueueBasicImpl();
		queueCpy.position = new Point(this.position.getX(), this.position.getY());
		queueCpy.size = this.size;
		queueCpy.action = this.action;
		
		return queueCpy;
	}
	
	private Image img;
	private Integer size = 0;
	private String action = "";
	private Point position;
	
}
